"use client";

import { useEffect, useState } from "react";
import type { CustomCellRendererProps } from "ag-grid-react";
import { ColDef } from "ag-grid-community";
import DataGrid from "@/components/data-grid";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { PlatformDialog } from "./platform-dialog";
import { Button } from "@/components/ui/button";
import { CookieDialog } from "../cookies/cookie-dialog";
import { IPlatform } from "../types";
const PlatformPage = () => {
  const queryClient = useQueryClient();
  const [rowData, setRowData] = useState<{}[]>([]);
  const [cokOpen, setCokOpen] = useState(false);
  const [platform, setPlatform] = useState<IPlatform | null>(null);
  const platformQuery = useQuery({
    queryKey: ["platforms"],
    queryFn: () =>
      fetch(`/api/platform/list`, {
        method: "GET",
        //credentials: "include",
      }).then((res) => {
        if (res.ok) {
          return res.json();
        } else {
          toast.error(" task page please login");
          setRowData([]);
        }
      }),
  });
  useEffect(() => {
    if (platformQuery.isPending) return;
    setRowData(platformQuery.data);
  }, [platformQuery]);
  const platformActionsRender = (params: CustomCellRendererProps) => {
    const { data: platform } = params;
    return (
      <div className="flex flex-row">
        <Button
          variant={"link"}
          onClick={() => {
            setPlatform(params.data);
            setCokOpen(true);
          }}
        >
          添加cookie
        </Button>
        <Button
          variant={"link"}
          onClick={() => {
            fetch(`/api/platform/${platform.id}`, { method: "DELETE" })
              .then((resp) => {
                if (resp.ok) {
                  toast.info(`Delete ${platform.name} successfully`);
                  queryClient.invalidateQueries({ queryKey: ["platforms"] });
                } else {
                  toast.error(`Delete ${platform.name} failed`);
                }
              })
              .catch((err) => {
                toast.error(`Exception delete ${platform.name} ${err}`);
              });
          }}
        >
          删除
        </Button>
      </div>
    );
  };
  const columnDefs: ColDef[] = [
    { field: "id", headerName: "ID", width: 100 },
    { field: "name", headerName: "平台", flex: 1 },
    { field: "url", headerName: "地址", flex: 1 },
    {
      field: "操作",
      headerName: "Actions",
      flex: 1,
      pinned: "right",
      cellRenderer: platformActionsRender,
    },
  ];
  return (
    <div className="flex flex-col flex-grow">
      <div className="flex justify-start">
        <PlatformDialog />
        <CookieDialog
          hastrigger={false}
          platform={platform}
          open={cokOpen}
          setOpenAction={setCokOpen}
        />
      </div>
      <DataGrid columnDefs={columnDefs} rowData={rowData} />
    </div>
  );
};
export default PlatformPage;
